Ext.namespace('SLM');

SLM.DwcGrid = function(config) {

	var Collection = Ext.data.Record.create([
			{name: 'land_id'}
		,	{name: 'Kingdom'}
		,	{name: 'Family'}
		, 	{name: 'ScientificName'}
		,	{name: 'property'}
		,	{name: 'title'}
		,	{name: 'Id'}
	]);
	
	var myReader = new Ext.data.JsonReader({
			totalProperty: "total"
		,	root: "records"
		,	id: "Id"
	}, Collection );
	
	this.proxy ="";
	if (Config.mode == 'local') {
		this.proxy = new Ext.data.HttpProxy({
			url: Config.baseUrl + 'resources/api/app.php'
		});
	} else {
		this.proxy = new Ext.data.ScriptTagProxy({
			url: Config.baseUrl + 'resources/api/app.php'
		})
	}
	this.store = new Ext.data.GroupingStore({
			reader: myReader
		,	proxy: this.proxy
		,	baseParams: { cmd: 'dwc-list' }
		,	sortInfo:{field: 'ScientificName', direction: "ASC"}			
		,	remoteSort: true
		,	autoLoad: true
	}, this);
	
	this.store.on('load',function(){
			this.enableDisbleEvent();
	},this);

  var pagingBar = new Ext.PagingToolbar({
			pageSize: 100
		,	store: this.store
		,	displayInfo: true
		,	displayMsg: 'Displaying Species {0} - {1} of {2}'
		,	emptyMsg: "No species to display"
	});
	this.filters = new Ext.ux.grid.GridFilters({
		encode: true
	,	filters: [{
				type: 'string'
			,	dataIndex: 'Family'
		}, {
				type: 'string'
			,	dataIndex: 'ScientificName'
		}, {
				type: 'string'
			,	dataIndex: 'property'
		}]
	});
	this.sm =	new Ext.grid.RowSelectionModel({
			singleSelect: true
		,	listeners: {
					rowselect: function(sm, row, rec){
						this.enableDisbleEvent();
					}
				,	rowdeselect: function(sm, row, rec){
						this.enableDisbleEvent();
					}
				,	scope: this	
			}
	});
	Ext.apply(this, config, {
			id: 'dwc'
		,	iconCls: 'icon_collections'
		,	columns: [
					{header: "Family", id: 'name', width: 110, dataIndex: 'Family', sortable: true}
				,	{header: "Species", width: 185, dataIndex: 'ScientificName', sortable: true}
				,	{header: "Property", width: 200, dataIndex: 'title', sortable: true}
			]
		,	border: false
		,	sm: this.sm
		, 	loadMask: true
		,	plugins: [ this.filters ]
		,	bbar: pagingBar
		,	view: new Ext.grid.GroupingView({
					groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "" : ""]})'
				,	emptyText: 'No species to display.'
			})	
		,	listeners: {
					rowcontextmenu: this.rightClickMenu	
			}
	});

	SLM.DwcGrid.superclass.constructor.apply(this, arguments);

};

Ext.extend( SLM.DwcGrid, Ext.grid.GridPanel, {
	enableDisbleEvent: function(){
		selection = this.getSelectionModel().getSelected();
		var found = false;
		if(Ext.isDefined(selection)){
			var selected = selection.data;
			found = this.checkLandId(selected.land_id);
		}
		if (Ext.getCmp('btn-delete-species')) {
			if (this.getSelectionModel().getCount() > 0 && found) {
				Ext.getCmp('btn-delete-species').enable();							
			} else {
				Ext.getCmp('btn-delete-species').disable();
			}
		}
	}
,	removeRequest: function(record){
		var confirmMsg = String.format('Are you sure you would like to remove species "{0}" from property "{1}"', record.ScientificName, record.title);
		Ext.Msg.confirm('Confirm', confirmMsg, function(btn){
				if(btn == 'yes'){
					var myMask = new Ext.LoadMask(this.body,{msg: 'Please wait...'});
					myMask.show();
					Ext.Ajax.request({
							url: Config.baseUrl + 'resources/api/app.php'
						,	scope: this
						,	params: { 
									cmd: 'removeSpecies'
								,	species_id: record.Id
							}
						,	success: function(response) {
								var o = Ext.decode(response.responseText);
								if(o.success){
									this.getStore().reload();
								}else {
									Ext.Msg.alert('Error', o.error.msg);
								}
								myMask.hide();	
							}
						,	failure: function(){
								Ext.Msg.alert('Error', 'Fatal Error.');
								myMask.hide();
							}	
					});
				}
		},this);	
	}
,	checkLandId: function(landId){
		var allowedLand = Ext.getCmp('dwc-panel').allowedLand;
		var found = false;
		for(var i=0; i<allowedLand.length; i++){
			if(allowedLand[i] == landId){
				found = true;
				break;
			}
		}
		return found;
	}
,	rightClickMenu: function(grid, row, e){
		grid.getSelectionModel().selectRow(row);
		var record = grid.getSelectionModel().getSelected().data;
		var items = []
		var found = this.checkLandId(record.land_id);
		if(found){
			items.push({
					text: 'Remove Species'
				,	iconCls: 'icon_events_delete'
				,	scope: this	
				,	handler: function(me) {
						this.removeRequest(record);
					}  
			},'-');
		}
		items.push({			
				text: 'GBIF Checklist Bank'
			,	iconCls:'icon_gbif'
			,	scope: this
			,	handler: function(){
					window.open('http://ecat-dev.gbif.org/search?q=' + record.ScientificName + '&rkey=1', '_blank');
				}
			},{
				text: 'ITIS: Catalog of Life'
			,	iconCls: 'icon_itis'
			,	handler: function(){
					window.open('http://www.catalogueoflife.org/annual-checklist/2010/search/all/key/' + record.ScientificName+ 'match/1', '_blank');
				}
			}, {
				text:'International Plant Names Index'
			,	handler: function() {
					window.open( 'http://www.ipni.org/ipni/advPlantNameSearch.do?find_infraspecies=&find_infragenus=&find_publicationTitle=&find_includePublicationAuthors=on&find_isIKRrecord=on&find_species=' + record.ScientificName + '&find_isGCIRecord=on&find_authorAbbrev=&find_includeBasionymAuthors=on&find_infrafamily=&find_genus=' + record.Genus + '&find_family=&find_isAPNIRecord=on', '_blank');
				}
			},{
				text: 'GBIF'
			,	iconCls: 'icon_gbif'
			,	scope: this
			,	handler: function(){
					window.open('http://data.gbif.org/search/' + record.ScientificName + '?', '_blank');
				}
			}, {
				text:'Flora of North America'
			,	iconCls: 'icon_fna'
			,	handler: function() {
					window.open( 'http://www.efloras.org/browse.aspx?name_str=' + record.ScientificName, '_blank');
				}
			}, {
				text:'NatureServe'
			,	iconCls: 'icon_natureserve'
			,	handler: function() {
					window.open( 'http://www.natureserve.org/explorer/servlet/NatureServe?searchName=' + record.ScientificName, '_blank');
				}
			}, {
				text:'USDA PLANTS'
			,	iconCls: 'icon_usda'
			,	handler: function() {
					window.open( 'http://plants.usda.gov/java/nameSearch?keywordquery=' + record.ScientificName + '&mode=sciname', '_blank');
				}
			}, {
				text:'Tropicos'
			,	iconCls: 'icon_fna'
			,	handler: function() {
					window.open( 'http://www.tropicos.org/NameSearch.aspx?name=' + record.ScientificName, '_blank');
				}
			}, {
				text:'Biodiversity Heritage Library'
			,	iconCls: 'icon_bhl'
			,	handler: function() {
					window.open( 'http://www.biodiversitylibrary.org/Search.aspx?searchTerm=' + record.ScientificName + '&searchCat=N', '_blank');
				}
			}, '-', {
				text:'Google Images'
			,	iconCls: 'icon_google'
			,	handler: function() {
					window.open( 'http://www.google.com/images?safe=yes&q=%22' + record.ScientificName + '%22', '_blank');
				}
			}, {
				text:'Flickr'
			,	iconCls: 'icon_flickr'
			,	handler: function() {
					window.open( 'http://www.flickr.com/search/?q=' + record.ScientificName, '_blank');
				}
			}, {
				text:'PicSearch'
			,	handler: function() {
					window.open( 'http://www.picsearch.com/search.cgi?q=' + record.ScientificName + '&cols=5&thumbs=20'	, '_blank');
				}
			})
		var menu = new Ext.menu.Menu({
				items: items
		});
		var xy = e.getXY();
		menu.showAt(xy);
	}
});